let logger = require("pomelo-logger").getLogger(__filename);

module.exports = function (app) {
    return new Remote(app);
};

let Remote = function (app) {
    this.app = app;
};

Remote.prototype.logout = function (frontendId, sessionId, callback) {
    logger.info("frontendId=" + frontendId + " sessionId=" + sessionId + " logout");
    let playerService = this.app.get("playerService");
    let player = playerService.findByConnectionId(frontendId, sessionId);
    if (player != null) {
        let game = player.getPlayingGame();
        if (game != null) {
            this.app.rpc[game.getName()].gameRemote.notifyPlayerOffline(null, {
                frontendId: frontendId,
                sessionId: sessionId
            }, function () {
                logger.info("notify game server offline. uid=" + player.getUid() + " game name=" + game.getName());
            });
        }
    }
    playerService.logout(frontendId, sessionId);
    callback(null);
};

Remote.prototype.getToken = function (msg, callback) {
    let playerService = this.app.get("playerService");
    playerService.getToken(msg, function (player) {
        if (!player) {
            logger.error("loginRemote getToken msg=" + JSON.stringify(msg) + " failed");
            callback({resultCode : -100, message: "获取token失败"});
            return;
        }
        logger.info("loginRemote getToken msg=" + JSON.stringify(msg) + " success. uid=" + player.getUid());
        callback({resultCode : 0, uid: player.getUid(), token: player.getToken(), tokenRefreshTime: player.getRefreshTokenTime()});
    });
};